#include "file_base_c.h"

bool file_base::open(kcstr _filename, kcstr _mode)
{
    close();

    m_file_ptr = fopen(_filename, _mode);
    if (is_open())
    {
        m_file_name = cmn::alloc_mem_from_str(_filename);
		seek(0, file::tail);
        m_length = tell();
		seek(0, file::head);
        return true;
    }
    return false;
}

bool file_base::open(kcwstr _filename, kcwstr _mode)
{
	close();

	m_file_ptr = _wfopen(_filename, _mode);
	if (is_open())
	{
		m_file_name = cmn::alloc_mem_from_wstr(_filename);
		seek(0, file::tail);
		m_length = tell();
		seek(0, file::head);
		return true;
	}
	return false;
}


void file_base::close()
{
    if (is_open())
    {
        fclose(m_file_ptr);
        m_file_ptr	= nullptr;
        m_length	= 0;
        m_file_name.free();
    }
}

bool file_base::seek(dword _offset, file::seek_dir _dir)
{
    int origin_enum[] = { SEEK_SET, SEEK_END, SEEK_CUR };
	return (0 == fseek(m_file_ptr, _offset, origin_enum[_dir]));
}

dword file_base::write(const void* _mem, dword _size)
{
    dword length = fwrite(_mem, _size, 1, m_file_ptr);
    m_length += length;
    return length;
}

mem io::def_read_whole_file(kcstr _filename)
{
    ifile* f = read_file(_filename);
    if (f)
    {
        mem m = cmn::alloc_mem(f->length());
        if (m.is_vaild())
        {
            f->read(m, f->length());
        }
		f->release();
        return m;
    }
    return mem();
}

mem io::def_read_whole_file(kcwstr _filename)
{
	ifile* f = read_file(_filename);
	if (f)
	{
		mem m = cmn::alloc_mem(f->length());
		if (m.is_vaild())
		{
			f->read(m, f->length());
		}
		f->release();
		return m;
	}
	return mem();
}
